<template>
  <div class="list">
    <div
      class="item border-gray-300 border-t p-2 text-sm cursor-pointer transition-all duration-200"
      :class="{
        'bg-white hover:bg-gray-100 text-gray-500': item.id !== conversationStore.selectId,
        'bg-blue-100 text-blue-800 border-l-4 border-l-blue-500 pl-1 shadow-sm':
          item.id === conversationStore.selectId
      }"
      v-for="item in items"
      :key="item.id"
      @click="handleClick(item.id)"
    >
      <div class="flex justify-between leading-6">
        <a href="#" :class="{ 'font-medium': item.id === conversationStore.selectId }">
          {{ item.selectModel }}
        </a>
        <span>{{ dayjs(item.updateAt).format('YYYY-MM-DD') }}</span>
      </div>
      <h2
        class="mt-4 font-bold leading-6 text-gray-900 truncate"
        :class="{ 'text-blue-900': item.id === conversationStore.selectId }"
      >
        {{ item.title }}
      </h2>
    </div>
  </div>
</template>

<script setup lang="ts">
  import type { ConversationProps } from '../type'
  import { useRouter, useRoute } from 'vue-router'
  import dayjs from 'dayjs'
  import useConversationStore from '../store/modules/converstaionStore'
  import { watch, onMounted } from 'vue'

  defineProps<{
    items: ConversationProps[]
  }>()

  const router = useRouter()
  const route = useRoute()
  const conversationStore = useConversationStore()

  // 处理点击事件
  const handleClick = (id: number) => {
    // 设置选中的会话ID
    conversationStore.setSelectId(id)

    // 导航到聊天页面
    router.push({
      path: '/chat',
      query: { id }
    })
  }

  // 组件挂载时，根据当前路由设置选中ID
  onMounted(() => {
    const currentId = route.query.id
    if (currentId) {
      conversationStore.setSelectId(Number(currentId))
    }
  })

  // 监听路由变化，更新选中ID
  // watch(
  //   () => route.query.id,
  //   newId => {
  //     if (newId) {
  //       conversationStore.setSelectId(Number(newId))
  //     }
  //   }
  // )
</script>

<style scoped>
  .item {
    transition: all 0.2s ease;
  }

  .item:hover {
    transform: translateX(2px);
  }
</style>
